/*
 * Created on 20.07.2008
 *
 */
package com.appspot.yttv.client;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;


/**
 *  JsonRequest
 *  http://www.gwtsite.com/how-to-access-web-services-with-gwt/
 *  
 * @author Uwe Maurer
 */
public class JsonRequest {
	
	public interface JsonRequestHandler {
		public void onRequestComplete(JavaScriptObject json);
	}

	public static void get(String url, JsonRequestHandler handler) {
		String callbackName = "JSONCallback" + handler.hashCode();
		get(url + callbackName, callbackName, handler);
	}

	public static void get(String url, String callbackName, JsonRequestHandler handler) {
		createCallbackFunction(handler, callbackName);
		addScript(url);
	}

	public static native void addScript(String url) /*-{
	    var scr = document.createElement("script");
	    scr.setAttribute("language", "JavaScript");
	    scr.setAttribute("src", url);
	    document.getElementsByTagName("body")[0].appendChild(scr);
	  }-*/;

	private native static void createCallbackFunction(JsonRequestHandler obj, String callbackName)/*-{
		    tmpcallback = function(j) {
		      obj.@com.appspot.yttv.client.JsonRequest$JsonRequestHandler::onRequestComplete(Lcom/google/gwt/core/client/JavaScriptObject;)(j);
		    };
		    eval( "window." + callbackName + "=tmpcallback" );
		  }-*/;
	
	public static void doFetchURL(String url, RequestCallback handler) {
		RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url);
	   
		try {
			requestBuilder.sendRequest(null, handler);
		} catch (RequestException ex) {
			int i =0;
			i++;
		}
		
	  }
}